import store from '../../store/store';
import {eventBus, Gisevevts} from '../../script/events'

let currentLayer;

//初始化地图
export const initMap = function (log) {
  console.log("init:" + log);
  initFrame(L.CRS.EPSG3857);
  currentLayer = L.tileLayer(
      "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
  );
  currentLayer.addTo(leafletMap);

  document.getElementById("mapContainer").style.zIndex = 0;
};


//加载JSON数据
export const loadGeoJson = function (file) {
  // console.log("接收到了参数：" + file);
  // $.getJSON('static/data/YellowRiver_gcj02.json', (data) => {
  let layerGeo = L.geoJSON(file, {
    fillColor: "#FF0000",
    fillOpacity: 0.5,
    color: "#FF0000",
    weight: 1
  });
  layerGeo.addTo(leafletMap);
  eventBus.$emit(Gisevevts["handlerAddGeojson"], layerGeo);
  // leafletMap.fitBounds(layerGeo.getBounds());
  leafletMap.flyToBounds(layerGeo.getBounds());
  // });
};

//切换底图
export const changeBaseMap = function (type) {
  //获取当前的矩形
  let tempRectangle = getRectangle();
  //移除当前底图
  currentLayer.remove();
  unloadMapFrame();
  if (type === 'baidu') {
    initFrame(L.CRS.Baidu, type);
    let styles = "t%3Awater%7Ce%3Aall%7Cc%3A%230b2a3fff%2Ct%3Ahighway%7Ce%3Ag.f%7Cc%3A%2322425cff%2Ct%3Aarterial%7Ce%3Ag.s%7Cc%3A%231b374eff%2Ct%3Alocal%7Ce%3Ag.f%7Cc%3A%231b374eff%2Ct%3Aland%7Ce%3Aall%7Cc%3A%231e394dff%2Ct%3Arailway%7Ce%3Ag%7Cv%3Aoff%7Cc%3A%23000000ff%2Ct%3Asubway%7Ce%3Ag%7Cv%3Aoff%2Ct%3Abuilding%7Ce%3Ag.f%7Cc%3A%23000000ff%2Ct%3Aall%7Ce%3Al.t.f%7Cc%3A%23857f7f%2Ct%3Aall%7Ce%3Al.t.s%7Cc%3A%23020d17ff%2Ct%3Abuilding%7Ce%3Ag%7Cv%3Aon%7Cc%3A%231e394eff%2Ct%3Agreen%7Ce%3Ag%7Cv%3Aoff%7Cc%3A%23153145ff%2Ct%3Aboundary%7Ce%3Aall%7Cc%3A%23656a7aff%2Ct%3Amanmade%7Ce%3Ag%7Cc%3A%2324475aff%2Ct%3Apoi%7Ce%3Aall%7Cv%3Aoff%2Ct%3Aall%7Ce%3Al.i%7Cv%3Aoff%2Ct%3Aall%7Ce%3Al.t.f%7Cv%3Aon%7Cc%3A%236b9ac3ff%2Ct%3Ahighway%7Ce%3Ag.s%7Cv%3Aon%7Cc%3A%23132d45ff%2Ct%3Aarterial%7Ce%3Ag.f%7Cc%3A%23162e45ff%2Ct%3Alocal%7Ce%3Ag.s%7Cc%3A%231a324aff";
    currentLayer = L.tileLayer.baidu({layer: 'custom', styles: styles});//自编辑样式
    // currentLayer = L.tileLayer.baidu({ layer: 'custom',customid:'grayscale'});//默认预设样式dark,midnight,grayscale,hardedge,light,redalert,googlelite,grassgreen,pink,darkgreen,bluish
    // currentLayer = L.tileLayer.baidu({ layer: 'img_d'});//百度卫星
    // currentLayer = L.tileLayer.baidu({ layer: 'img'});//百度卫星+注记
    currentLayer.addTo(leafletMap);
  } else if (type === 'gaode') {
    initFrame(L.CRS.EPSG3857, type);//
    currentLayer = L.tileLayer('http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {});
    currentLayer.addTo(leafletMap);
  } else if (type === 'tianditu') {
    initFrame(L.CRS.EPSG3857, type);//L.CRS.EPSG4326  //4326出不来天地图
    // currentLayer = L.tileLayer.chinaProvider('Arcgis.Normal.Map', {maxZoom: 18, minZoom: 0});
    // currentLayer = L.tileLayer.chinaProvider('Google.Normal.Map', {maxZoom: 23, minZoom: 0});

    currentLayer = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {key: "53fa4c6322d455b68afac58ecc41d941"}).addTo(leafletMap);//自己申请的key
    // currentLayer = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion',{maxZoom:18,minZoom:5,key:"73ce9d0155c8c10c44b0c60f94d65c13"}).addTo(leafletMap);


    // currentLayer =  L.layerGroup([
    //   L.tileLayer('http://t{s}.tianditu.cn/DataServer?T=img_w&X={x}&Y={y}&L={z}', {  subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
    //   L.tileLayer('http://t{s}.tianditu.cn/DataServer?T=cia_w&X={x}&Y={y}&L={z}', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
    // ]);

    // currentLayer =  L.tileLayer('http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}', {
    //   maxZoom: 13,
    //   minZoom: 5,
    //   zoomOffset: 1
    // });

    // currentLayer = L.tileLayer('http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=53fa4c6322d455b68afac58ecc41d941');
    // currentLayer = L.tileLayer('http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=53fa4c6322d455b68afac58ecc41d941');


    // currentLayer = L.tileLayer('http://t3.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}', {
    //   maxZoom: 13,
    //   minZoom: 5,
    //   zoomOffset: 1
    // });
    // currentLayer.addTo(leafletMap);
  } else if (type === "arcgis") {
    initFrame(L.CRS.EPSG3857, type);
    //证明：L.esri.tiledMapLayer和L.tileLayer的加载效果一样。但是前者可以加载自己发布的服务,
    // currentLayer = L.esri.tiledMapLayer({url:"http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}"});
    currentLayer = L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}', {});//普通
    // currentLayer = L.tileLayer('https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',{});//影像
    // currentLayer = L.tileLayer('http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}',{});//普通
    currentLayer.addTo(leafletMap);
  } else if (type === '供应商') {
    initFrame(L.CRS.EPSG3857, type);
    // currentLayer = L.esri.tiledMapLayer({url:"http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/light_c/MapServer"});//亮色
    currentLayer = L.esri.tiledMapLayer({url: "http://111.26.1.82:6080/arcgis/rest/services//JLHBSLT/MapServer"});//亮色
    currentLayer.addTo(leafletMap);
  } else if (type === '暗色') {
    T
    initFrame(L.CRS.EPSG3857, type);
    currentLayer = L.esri.tiledMapLayer({url: "http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/dark_cnn/MapServer"});
    currentLayer.addTo(leafletMap);
  } else if (type === '新配图') {
    initFrame(L.CRS.EPSG3857, type);
    currentLayer = L.esri.tiledMapLayer({url: "http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/light_0923/MapServer"});
    currentLayer.addTo(leafletMap);
  } else if (type === 'geoserver') {
    console.log("加载GeoServer")
    initFrame(L.CRS.EPSG3857, type);//L.CRS.Baidu,type
    // currentLayer = new L.TileLayer.WMTS( "http://localhost:8888/geowebcache/service/wmts" ,//本机服务地址
    currentLayer = new L.TileLayer.WMTS("http://111.26.1.82:8888/geowebcache/service/wmts",//远程服务地址
        {
          layer: "ChangChunShi",//图层名称
          tilematrixSet: "EPSG:3857_ChangChunShi",//GeoServer使用的网格名称
          // tileSize : 256,//切片大小
          format: 'image/png',
        }
    );
    currentLayer.addTo(leafletMap);
  } else if (type === 'tianditu2') {
    initFrame(L.CRS.EPSG4326, type);//L.CRS.EPSG4326
    // L.tileLayer("http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=53fa4c6322d455b68afac58ecc41d941", {
    //   tileSize: 256,
    //   zoomOffset: 1,
    // }).addTo(leafletMap);
    //下面这个是天地图官网，提供的，密钥自己申请的 vec_c vec_w
    L.tileLayer("http://t0.tianditu.gov.cn/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=53fa4c6322d455b68afac58ecc41d941", {
      tileSize: 256,
      zoomOffset: 1,
    }).addTo(leafletMap);
  }
  setRectangle(tempRectangle);
};

//设置当前视图下的矩形区域
export const setRectangle = function (Bounds) {
  // console.log("显示bounds的值：" + JSON.initMapstringify(Bounds))
  leafletMap.fitBounds([
    [Bounds.south, Bounds.west],
    [Bounds.north, Bounds.east]
  ]);
  // leafletMap.fitBounds(leafletMap.latLngBounds(L.latLng([Bounds.south,Bounds.west]),L.latLng([Bounds.north,Bounds.east])));
};
//获取当前视图下的矩形区域
export const getRectangle = function () {
  let leftdown = leafletMap.getBounds().getSouthWest();
  let rightup = leafletMap.getBounds().getNorthEast();
  let rectangle = {
    'west': leftdown.lng,
    'south': leftdown.lat,
    'east': rightup.lng,
    'north': rightup.lat,
  };
  // console.log("leaflet边界：" + JSON.stringify(rectangle));
  return rectangle;
};


function initFrame(mapCrs, mapName = null) {
  window.leafletMap = L.map("mapContainer", {
    // minZoom: 3,
    // maxZoom: 14,
    center: [34.76, 113.6],
    zoom: 9,
    zoomControl: false,
    attributionControl: false,
    crs: mapCrs
  });
  store.state.currentFrameNameStore = 'leaflet';

  if (mapName) {
    eventBus.$emit(Gisevevts["handlerReloadMapFrame"], mapName);
  } else {
    eventBus.$emit(Gisevevts["handlerReloadMapFrame"], 'default');
  }
}

//重定位地图
export const relocation = function () {
  // leafletMap.setView(L.latLng(34.76, 113.6), 9);//郑州
  leafletMap.setView(L.latLng(42.973, 121.816), 4);//吉林
};

//卸载地图
export const unloadMapFrame = function () {
  leafletMap.off();
  leafletMap.remove();
  document.getElementById('mapContainer').style.backgroundImage = 'url(../../../static/image/bg_image.jpg)';
  store.state.currentFrameNameStore = '';
  window.leafletMap = null;
};

export const mapName = 'leaflet';

